/* +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+---------------------------------------------------------------------- */

import $util from "@/common/tools.js";
import permission from "@/common/permission.js";

class recorderUtil {
	// 构造函数
	constructor(maxRecorderTime) {
		// 获取全局唯一的录音管理器
		this.recorderManager = uni.getRecorderManager();
		// 是否运行
		this.isWorking = false;
		// 存储外部注册的消息回调函数的数组
		this.messageCallbacks = [];
		// 开始录音时间
		this.startTime = "";
		// 结束录音时间
		this.endTime = "";
		// 最长录音时间（秒）
		this.maxRecorderTime = maxRecorderTime || 60
		// 初始化录音管理器
		this.initRecode();
	}

	// 初始化录音管理器
	initRecode() {
		// status: 1.正在录音，2.未录音，3.录音暂停
		// 监听录音开始事件
		this.recorderManager.onStart(() => {
			this.isWorking = true;
			this.startTime = $util.getCurrentDate();
			this.messageCallbacks.forEach(callback => callback({ type: "start", status: 1 }));
		});

		// 监听录音暂停事件
		this.recorderManager.onPause(() => {
			this.messageCallbacks.forEach(callback => callback({ type: "pause", status: 3 }));
		});

		// 监听录音继续事件
		this.recorderManager.onResume(() => {
			this.messageCallbacks.forEach(callback => callback({ type: "resume", status: 1 }));
		});

		// 监听录音停止事件
		this.recorderManager.onStop((res) => {
			this.isWorking = false;
			this.endTime = $util.getCurrentDate();
			this.messageCallbacks.forEach(callback => callback({
				type: "stop",
				status: 2,
				path: res.tempFilePath,
				start_time: this.startTime,
				end_time: this.endTime,
			}));
		});
	}

	// 外部注册消息回调函数
	onMessage(callback) {
		this.messageCallbacks.push(callback);
	}

	// 检查并请求录音权限
	checkAndRequestRecordPermission() {
		return new Promise(async (resolve, reject) => {
			// #ifdef MP-WEIXIN
			uni.getSetting({
				success: (res) => {
					if (res.authSetting['scope.record']) {
						resolve(true);
					} else {
						uni.authorize({
							scope: 'scope.record',
							success: () => {
								resolve(true);
							},
							fail: () => {
								reject(new Error('用户拒绝授予录音权限'));
							}
						});
					}
				},
				fail: () => {
					reject(new Error('获取权限设置失败'));
				}
			});
			// #endif
			// #ifdef APP
			try {
				var isPermission = 2
				if (plus.os.name == "iOS") {
					isPermission = permission.judgeIosPermissionRecord() ? 1 : 2
				} else {
					isPermission = await permission.requestAndroidPermission("android.permission.RECORD_AUDIO")
				}
				if (isPermission == 1) {
					resolve(true);
				} else {
					reject(new Error('用户拒绝授予录音权限'));
				}
			} catch (error) {
				reject(new Error('录音权限获取失败'));
			}
			// #endif
		});
	}

	// 跳转APP系统设置
	gotoAppPermissionSetting() {
		permission.gotoAppPermissionSetting()
	}

	// 开始录音
	async startRecord() {
		try {
			// 检查并请求录音权限
			await this.checkAndRequestRecordPermission();
			if (this.isWorking) return;
			this.recorderManager.start({
				duration: this.maxRecorderTime * 1000,
				format: "mp3",
			});
		} catch (error) {
			this.messageCallbacks.forEach(callback => callback({
				type: "permission_denied",
				status: 2,
				error: error.message
			}));
		}
	}

	// 暂停录音
	pauseRecord() {
		if (!this.isWorking) return;
		this.recorderManager.pause();
	}

	// 继续录音
	resumeRecord() {
		if (!this.isWorking) return;
		this.recorderManager.resume();
	}

	// 结束录音
	endRecord() {
		if (!this.isWorking) return;
		this.isWorking = false;
		this.recorderManager.stop();
	}
}

export default recorderUtil;